﻿'
' DKP for DotNetNuke® - http://dkpdnn.codeplex.com
' Copyright (c) 2008
' by Casey Lengacher ( http://dkpdnn.codeplex.com )
'
' DotNetNuke®, DNN®, and the DotNetNuke logo are trademarks of DotNetNuke Corporation.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
'

Imports System.Xml
Imports System.Net
Imports DotNetNuke.Common.Utilities

Namespace DotNetNuke.Modules.tss_DKP

    Partial Public Class tss_ucPlayers

        Inherits Entities.Modules.PortalModuleBase

#Region "Private Variables"

        Private Enum PageState As Integer
            NotSet = -1
            View = 0
            Add = 1
            SingleUpdate = 2
            MultiUpdate = 3
        End Enum

#End Region

#Region "Private Properties"

        Private Property vsPageSize() As Integer
            Get
                If ViewState("dkpdnn_PlayerPageSize") Is Nothing Then
                    If (Request.Cookies.Get("dkpdnn_PlayerPageSize") Is Nothing) Then
                        Return ddlPageSize.Items(0).Value
                    Else
                        Return CInt(Request.Cookies.Get("dkpdnn_PlayerPageSize").Value)
                    End If
                Else
                    Return CInt(ViewState("dkpdnn_PlayerPageSize"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("dkpdnn_PlayerPageSize") = Value
                Response.Cookies("dkpdnn_PlayerPageSize").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("dkpdnn_PlayerPageSize").Value = Value
            End Set
        End Property

        Private Property vsSortExpression() As String
            Get
                If (ViewState("tss_PlayerSortExpression") Is Nothing) Then
                    If (Request.Cookies.Get("tss_PlayerSortExpression") Is Nothing) Then
                        Return "PlayerName"
                    Else
                        Return CStr(Request.Cookies.Get("tss_PlayerSortExpression").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_PlayerSortExpression"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_PlayerSortExpression") = Value
                Response.Cookies("tss_PlayerSortExpression").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_PlayerSortExpression").Value = Value
            End Set
        End Property

        Private Property vsSortDirection() As String
            Get
                If (ViewState("tss_PlayerSortDirection") Is Nothing) Then
                    If (Request.Cookies.Get("tss_PlayerSortDirection") Is Nothing) Then
                        Return "ASC"
                    Else
                        Return CStr(Request.Cookies.Get("tss_PlayerSortDirection").Value)
                    End If
                Else
                    Return CStr(ViewState("tss_PlayerSortDirection"))
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("tss_PlayerSortDirection") = Value
                Response.Cookies("tss_PlayerSortDirection").Expires = DateTime.Now.AddYears(10)
                Response.Cookies("tss_PlayerSortDirection").Value = Value
            End Set
        End Property

        Private Property vsCurrentPage() As Integer
            Get
                If (ViewState("tss_PlayerCurrentPage") Is Nothing) Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_PlayerCurrentPage"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_PlayerCurrentPage") = Value
            End Set
        End Property

        Private Property vsTotalPages() As Integer
            Get
                If (ViewState("tss_PlayerTotalPages") Is Nothing) Then
                    Return 1
                Else
                    Return CInt(ViewState("tss_PlayerTotalPages"))
                End If
            End Get
            Set(ByVal Value As Integer)
                ViewState("tss_PlayerTotalPages") = Value
            End Set
        End Property

        Private Property vsPageState() As PageState
            Get
                If (ViewState("tss_PlayerPageState") Is Nothing) Then
                    Return PageState.NotSet
                Else
                    Return CStr(ViewState("tss_PlayerPageState"))
                End If
            End Get
            Set(ByVal Value As PageState)
                ViewState("tss_PlayerPageState") = Value
            End Set
        End Property

#End Region

#Region "Private Methods"

        Private Sub BindPage()

            Dim tss_DKP As New tss_DataController
            Dim intRowsAffected As Integer
            Dim intPageNumber As Integer = vsCurrentPage
            Dim dblPagesAffected As Double = 1

            grdDeathKnights.DataSource = tss_DKP.tss_GetPlayersByClass("Death Knight", CInt(Settings("BoardID")))
            grdDeathKnights.DataBind()

            grdDruids.DataSource = tss_DKP.tss_GetPlayersByClass("Druid", CInt(Settings("BoardID")))
            grdDruids.DataBind()

            grdHunters.DataSource = tss_DKP.tss_GetPlayersByClass("Hunter", CInt(Settings("BoardID")))
            grdHunters.DataBind()

            grdMages.DataSource = tss_DKP.tss_GetPlayersByClass("Mage", CInt(Settings("BoardID")))
            grdMages.DataBind()

            grdPaladins.DataSource = tss_DKP.tss_GetPlayersByClass("Paladin", CInt(Settings("BoardID")))
            grdPaladins.DataBind()

            grdPriests.DataSource = tss_DKP.tss_GetPlayersByClass("Priest", CInt(Settings("BoardID")))
            grdPriests.DataBind()

            grdRogues.DataSource = tss_DKP.tss_GetPlayersByClass("Rogue", CInt(Settings("BoardID")))
            grdRogues.DataBind()

            grdShamans.DataSource = tss_DKP.tss_GetPlayersByClass("Shaman", CInt(Settings("BoardID")))
            grdShamans.DataBind()

            grdWarlocks.DataSource = tss_DKP.tss_GetPlayersByClass("Warlock", CInt(Settings("BoardID")))
            grdWarlocks.DataBind()

            grdWarriors.DataSource = tss_DKP.tss_GetPlayersByClass("Warrior", CInt(Settings("BoardID")))
            grdWarriors.DataBind()

            ddlPageSize.SelectedValue = ddlPageSize.Items.FindByText(vsPageSize).Value

            grdPlayers.PageSize = vsPageSize

            For Each currentColumn As DataGridColumn In grdPlayers.Columns
                currentColumn.HeaderText = currentColumn.HeaderText.Substring(0, _
                    IIf(currentColumn.HeaderText.IndexOf(" <img") > 0, currentColumn.HeaderText.IndexOf(" <img"), currentColumn.HeaderText.Length))
                If (currentColumn.SortExpression = vsSortExpression) Then
                    If (vsSortDirection = "ASC") Then
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_uparrow.png' border=0 height=10 width=10>"
                    Else
                        currentColumn.HeaderText = currentColumn.HeaderText _
                            + " <img src='/DesktopModules/tss_DKP/Images/grid_icon_downarrow.png' border=0 height=10 width=10>"
                    End If
                End If
            Next

            grdPlayers.DataSource = tss_DKP.tss_GetPlayersByPage(CInt(Settings("BoardID")), intPageNumber, grdPlayers.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
            grdPlayers.DataBind()

            If (grdPlayers.Items.Count = 0) And (intPageNumber > 1) Then
                intPageNumber = intPageNumber - 1
                vsCurrentPage = intPageNumber.ToString()
                grdPlayers.DataSource = tss_DKP.tss_GetPlayersByPage(CInt(Settings("BoardID")), intPageNumber, grdPlayers.PageSize, vsSortExpression, vsSortDirection, intRowsAffected)
                grdPlayers.DataBind()
            End If

            dblPagesAffected = System.Math.Ceiling(intRowsAffected / grdPlayers.PageSize)
            If (dblPagesAffected < 1) Then
                dblPagesAffected = 1
            End If
            vsTotalPages = dblPagesAffected.ToString()
            lblCurrentPage.Text = vsCurrentPage
            lblTotalPages.Text = vsTotalPages

            If (intPageNumber = 1) Then
                lnkPreviousPage.Enabled = False

                If (dblPagesAffected > 1) Then
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                Else
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                End If
            Else
                lnkPreviousPage.Enabled = True

                If (intPageNumber = dblPagesAffected) Then
                    lnkNextPage.Enabled = False
                    lnkLastPage.Enabled = False
                Else
                    lnkNextPage.Enabled = True
                    lnkLastPage.Enabled = True
                End If
            End If

            If (DotNetNuke.Security.PortalSecurity.IsInRoles(Me.ModuleConfiguration.AuthorizedEditRoles)) And Not (UserId = -1) Then
                pnlEditPanel.Visible = True
                grdPlayers.Columns(0).Visible = True
            Else
                pnlEditPanel.Visible = False
                grdPlayers.Columns(0).Visible = False
            End If

        End Sub

        Private Sub ManagePageState(ByVal PageState As PageState)

            Dim tss_DKP As New tss_DataController

            vsPageState = PageState

            If (PageState = PageState.View) Then
                grdPlayers.Enabled = True
                BindPage()
            Else
                grdPlayers.Enabled = False
            End If

            If (PageState = PageState.View) Then
                pnlEditPanelForm.Visible = False
            Else

                Dim objExistingBoard As tss_BoardInfo = tss_DKP.tss_GetBoard(CInt(Settings("BoardID")))

                ddlPlayerClass.DataTextField = "ClassName"
                ddlPlayerClass.DataValueField = "ClassName"
                ddlPlayerClass.DataSource = tss_DKP.tss_GetClasses(objExistingBoard.GameID)
                ddlPlayerClass.DataBind()

                ddlPlayerRace.DataTextField = "RaceName"
                ddlPlayerRace.DataValueField = "RaceName"
                ddlPlayerRace.DataSource = tss_DKP.tss_GetRaces(objExistingBoard.GameID)
                ddlPlayerRace.DataBind()

                ddlPlayerLevel.DataTextField = "LevelName"
                ddlPlayerLevel.DataValueField = "LevelName"
                ddlPlayerLevel.DataSource = tss_DKP.tss_GetLevels(objExistingBoard.GameID)
                ddlPlayerLevel.DataBind()

                pnlEditPanelForm.Visible = True

            End If

            txtPlayerName.Text = Null.NullString
            txtPlayerRank.Text = Null.NullString
            ddlPlayerClass.ClearSelection()
            ddlPlayerRace.ClearSelection()
            ddlPlayerLevel.ClearSelection()
            txtJoinDate.Text = Null.NullString

            lblWarning.Text = Null.NullString

            If (PageState = PageState.Add) Or (PageState = PageState.SingleUpdate) Then

                pnlPlayerName.Visible = True

                chkIncludePlayerName.Visible = False
                chkIncludePlayerRank.Visible = False
                chkIncludePlayerClass.Visible = False
                chkIncludePlayerRace.Visible = False
                chkIncludePlayerLevel.Visible = False
                chkIncludeJoinDate.Visible = False

                txtPlayerName.Focus()

            ElseIf (PageState = PageState.MultiUpdate) Then

                pnlPlayerName.Visible = False

                chkIncludePlayerRank.Visible = True
                chkIncludePlayerClass.Visible = True
                chkIncludePlayerRace.Visible = True
                chkIncludePlayerLevel.Visible = True
                chkIncludeJoinDate.Visible = True

                chkIncludePlayerRank.Checked = False
                chkIncludePlayerClass.Checked = False
                chkIncludePlayerRace.Checked = False
                chkIncludePlayerLevel.Checked = False
                chkIncludeJoinDate.Checked = False

                txtPlayerRank.Focus()

            End If

        End Sub

        Private Function SyncPlayers() As String

            Dim tss_DKP As New tss_DataController

            Dim webWoWArmory As New WebClient
            Dim xmlWoWArmory As XmlTextReader
            Dim strWarning As String = Null.NullString
            Dim txtURL As String = Null.NullString

            Dim objExistingBoard As tss_BoardInfo = tss_DKP.tss_GetBoard(CInt(Settings("BoardID")))

            If (objExistingBoard.GuildName = "") Or (objExistingBoard.RegionName = "") Or (objExistingBoard.RealmName = "") Then
                strWarning = "Error: Region, Realm and Guild values must be set before syncing is allowed."
            Else

                If (objExistingBoard.RegionName = "Europe") Then
                    txtURL = "http://eu.wowarmory.com/guild-info.xml"
                Else
                    txtURL = "http://www.wowarmory.com/guild-info.xml"
                End If

                webWoWArmory.QueryString.Add("r", objExistingBoard.RealmName)
                webWoWArmory.QueryString.Add("n", objExistingBoard.GuildName)
                webWoWArmory.Headers.Add("user-agent", "MSIE 7.0")

                xmlWoWArmory = New XmlTextReader(webWoWArmory.OpenRead(txtURL))

                Do While (xmlWoWArmory.Read)

                    If (xmlWoWArmory.NodeType = XmlNodeType.Element) Then

                        If (xmlWoWArmory.LocalName = "character") And (xmlWoWArmory.GetAttribute("level") >= objExistingBoard.PlayerSyncCutOff) Then

                            Dim objExistingPlayer As tss_PlayerInfo = tss_DKP.tss_GetPlayerByName(xmlWoWArmory.GetAttribute("name"), CInt(Settings("BoardID")))

                            If (objExistingPlayer Is Nothing) Then

                                Dim objNewPlayer As New tss_PlayerInfo : objNewPlayer = CBO.InitializeObject(objNewPlayer, GetType(tss_PlayerInfo))

                                objNewPlayer.PlayerName = xmlWoWArmory.GetAttribute("name")
                                objNewPlayer.PlayerRank = xmlWoWArmory.GetAttribute("rank")
                                objNewPlayer.PlayerClass = MapClassName(xmlWoWArmory.GetAttribute("classId"))
                                objNewPlayer.PlayerRace = MapRaceName(xmlWoWArmory.GetAttribute("raceId"))
                                objNewPlayer.PlayerLevel = xmlWoWArmory.GetAttribute("level")
                                objNewPlayer.JoinDate = Now
                                objNewPlayer.BoardID = CInt(Settings("BoardID"))

                                Try
                                    tss_DKP.tss_AddPlayer(objNewPlayer)
                                Catch ex As ApplicationException
                                    strWarning = strWarning + IIf(strWarning.Length > 0, "<br>", "") _
                                        + "Error: Trying to add player (" + objNewPlayer.PlayerName _
                                        + ") via sync resulted in the following error (" + ex.Message + ")."
                                End Try

                            Else

                                objExistingPlayer.PlayerRank = xmlWoWArmory.GetAttribute("rank")
                                objExistingPlayer.PlayerClass = MapClassName(xmlWoWArmory.GetAttribute("classId"))
                                objExistingPlayer.PlayerRace = MapRaceName(xmlWoWArmory.GetAttribute("raceId"))
                                objExistingPlayer.PlayerLevel = xmlWoWArmory.GetAttribute("level")

                                Try
                                    tss_DKP.tss_UpdatePlayer(objExistingPlayer)
                                Catch ex As ApplicationException
                                    strWarning = strWarning + IIf(strWarning.Length > 0, "<br>", "") _
                                        + "Error: Trying to update player (" + objExistingPlayer.PlayerName _
                                        + ") via sync resulted in the following error (" + ex.Message + ")."
                                End Try

                            End If

                        End If

                    End If

                Loop

            End If

            Return strWarning

        End Function

        Private Function MapClassName(ByVal strClassID) As String

            Select Case strClassID
                Case "1"
                    Return "Warrior"
                Case "2"
                    Return "Paladin"
                Case "3"
                    Return "Hunter"
                Case "4"
                    Return "Rogue"
                Case "5"
                    Return "Priest"
                Case "6"
                    Return "Death Knight"
                Case "7"
                    Return "Shaman"
                Case "8"
                    Return "Mage"
                Case "9"
                    Return "Warlock"
                Case "11"
                    Return "Druid"
            End Select

            Return Null.NullString

        End Function

        Private Function MapRaceName(ByVal strRaceID) As String

            Select Case strRaceID
                Case "1"
                    Return "Human"
                Case "2"
                    Return "Orc"
                Case "3"
                    Return "Dwarf"
                Case "4"
                    Return "Night Elf"
                Case "5"
                    Return "Undead"
                Case "6"
                    Return "Tauren"
                Case "7"
                    Return "Gnome"
                Case "8"
                    Return "Troll"
                Case "10"
                    Return "Blood Elf"
                Case "11"
                    Return "Draenei"
            End Select

            Return Null.NullString

        End Function

#End Region

#Region "Private Event Handlers"

        Private Sub ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdPlayers.ItemDataBound

            Dim tss_DKP As New tss_DataController
            Dim objExistingBoard As tss_BoardInfo = tss_DKP.tss_GetBoard(CInt(Settings("BoardID")))

            If (e.Item.ItemType.Equals(ListItemType.Item)) Or (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                Dim lblPlayerID As Label = e.Item.FindControl("lblPlayerID")
                Dim btnPlayerDetails As ImageButton = e.Item.FindControl("btnPlayerDetails")
                Dim lblPlayerName As Label = e.Item.FindControl("lblPlayerName")
                Dim lblPlayerRank As Label = e.Item.FindControl("lblPlayerRank")
                Dim lblPlayerClass As Label = e.Item.FindControl("lblPlayerClass")
                Dim lblPlayerRace As Label = e.Item.FindControl("lblPlayerRace")
                Dim lblPlayerLevel As Label = e.Item.FindControl("lblPlayerLevel")
                Dim lblEarnedDKP As Label = e.Item.FindControl("lblEarnedDKP")
                Dim lblSpentDKP As Label = e.Item.FindControl("lblSpentDKP")
                Dim lblSavedDKP As Label = e.Item.FindControl("lblSavedDKP")
                Dim lblJoinDate As Label = e.Item.FindControl("lblJoinDate")
                Dim lblRaidAttendanceLast30Days As Label = e.Item.FindControl("lblRaidAttendanceLast30Days")

                Dim objPlayer As tss_PlayerInfo = e.Item.DataItem

                lblPlayerID.Text = objPlayer.PlayerID.ToString()
                lblPlayerID.Visible = False

                btnPlayerDetails.ImageUrl = "/DesktopModules/tss_DKP/Images/grid_icon_magnifier.png"
                btnPlayerDetails.CommandName = "PlayerDetails"
                btnPlayerDetails.CommandArgument = objPlayer.PlayerID.ToString()
                btnPlayerDetails.AlternateText = "View Raids and Loots"

                lblPlayerName.Text = objPlayer.PlayerName
                lblPlayerRank.Text = objPlayer.PlayerRank
                lblPlayerClass.Text = objPlayer.PlayerClass
                lblPlayerRace.Text = objPlayer.PlayerRace
                lblPlayerLevel.Text = objPlayer.PlayerLevel
                lblEarnedDKP.Text = objPlayer.EarnedDKP.ToString()
                lblSpentDKP.Text = objPlayer.SpentDKP.ToString()

                If (objPlayer.SavedDKP > 0) Then
                    lblSavedDKP.CssClass = "dkpdnn_GridGoodTextColor"
                ElseIf (objPlayer.SavedDKP < 0) Then
                    lblSavedDKP.CssClass = "dkpdnn_GridBadTextColor"
                End If
                lblSavedDKP.Text = objPlayer.SavedDKP.ToString()

                lblJoinDate.Text = objPlayer.JoinDate.ToString("MM/dd/yy hh:mm tt")

                If (objPlayer.RaidAttendanceLast30Days >= objExistingBoard.GoodAttendanceCutOff) Then
                    lblRaidAttendanceLast30Days.CssClass = "dkpdnn_GridGoodTextColor"
                ElseIf (objPlayer.RaidAttendanceLast30Days < objExistingBoard.BadAttendanceCutOff) Then
                    lblRaidAttendanceLast30Days.CssClass = "dkpdnn_GridBadTextColor"
                End If
                lblRaidAttendanceLast30Days.Text = objPlayer.RaidAttendanceLast30Days.ToString() _
                    + " % (" + objPlayer.RaidsAttendedLast30Days.ToString() + "/" + objPlayer.RaidsLast30Days.ToString() + ")"

            End If

        End Sub

        Private Sub ItemCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles grdPlayers.ItemCommand

            Dim tss_DKP As New tss_DataController
            Dim tss_DKP_Parent As tss_DKP = Me.Parent.Parent

            If (e.CommandName = "PlayerDetails") Then

                Dim objPlayer As tss_PlayerInfo = tss_DKP.tss_GetPlayer(CInt(e.CommandArgument))
                If (objPlayer Is Nothing) Then
                    ManagePageState(PageState.View)
                    lblWarning.Text = "Error: Player not found."
                Else
                    tss_DKP_Parent.lnkManagePlayerDetails_Click(objPlayer)
                End If

            End If

        End Sub

        Private Sub ItemCreated(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdPlayers.ItemCreated

            If (e.Item.ItemType.Equals(ListItemType.Header)) Then

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridHeader" + grdPlayers.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Item)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridItem" + grdPlayers.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.AlternatingItem)) Then

                e.Item.Attributes.Add("class", "dkpdnn_GridAltItem")
                e.Item.Attributes.Add("onmouseover", "className='dkpdnn_GridAltItemMouseOver';")
                e.Item.Attributes.Add("onmouseout", "className='dkpdnn_GridAltItem';")

                For Each currentCell As TableCell In e.Item.Cells
                    currentCell.Attributes.Add("class", "dkpdnn_GridAltItem" + grdPlayers.Columns(e.Item.Cells.GetCellIndex(currentCell)).FooterText)
                Next

            ElseIf (e.Item.ItemType.Equals(ListItemType.Footer)) Then

                e.Item.Visible = False

            End If

        End Sub

        Private Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlPageSize.SelectedIndexChanged

            If (sender.Equals(ddlPageSize)) Then

                vsPageSize = ddlPageSize.SelectedValue
                ManagePageState(PageState.View)

            End If

        End Sub

        Private Sub SortCommand(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs) Handles grdPlayers.SortCommand

            If (vsSortExpression = e.SortExpression) Then
                If (vsSortDirection = "ASC") Then
                    vsSortDirection = "DESC"
                ElseIf (vsSortDirection = "DESC") Then
                    vsSortDirection = "ASC"
                End If
            Else
                vsSortExpression = e.SortExpression
                vsSortDirection = "ASC"
            End If

            ManagePageState(PageState.View)

        End Sub

        Private Sub Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkFirstPage.Click, lnkPreviousPage.Click, lnkNextPage.Click, _
            lnkLastPage.Click, lnkAdd.Click, lnkUpdate.Click, lnkDelete.Click, lnkSync.Click, lnkSubmit.Click, lnkCancel.Click

            Dim tss_DKP As New tss_DataController

            lblWarning.Text = Null.NullString

            If (sender.Equals(lnkFirstPage)) Then

                vsCurrentPage = 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkPreviousPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) - 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkNextPage)) Then

                vsCurrentPage = CInt(vsCurrentPage) + 1
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkLastPage)) Then

                vsCurrentPage = vsTotalPages
                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkAdd)) Then

                ManagePageState(PageState.Add)

            ElseIf (sender.Equals(lnkUpdate)) Then

                Dim boolIsChecked As Boolean = False

                For Each currentPlayer As DataGridItem In grdPlayers.Items

                    If (currentPlayer.ItemType.Equals(ListItemType.Item)) Or (currentPlayer.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkPlayer As CheckBox = currentPlayer.FindControl("chkPlayer")
                        Dim lblPlayerID As Label = currentPlayer.FindControl("lblPlayerID")

                        If (chkPlayer.Checked) And (boolIsChecked) Then

                            ManagePageState(PageState.MultiUpdate)
                            Exit For

                        ElseIf (chkPlayer.Checked) And Not (boolIsChecked) Then

                            boolIsChecked = True

                            ManagePageState(PageState.SingleUpdate)

                            Dim objExistingPlayer As tss_PlayerInfo = tss_DKP.tss_GetPlayer(CInt(lblPlayerID.Text))

                            If (objExistingPlayer Is Nothing) Then
                                ManagePageState(PageState.View)
                                lblWarning.Text = "Error: Player in selection not found."
                                Exit For
                            Else
                                txtPlayerName.Text = objExistingPlayer.PlayerName
                                txtPlayerRank.Text = objExistingPlayer.PlayerRank
                                ddlPlayerClass.SelectedValue = objExistingPlayer.PlayerClass
                                ddlPlayerRace.SelectedValue = objExistingPlayer.PlayerRace
                                ddlPlayerLevel.SelectedValue = objExistingPlayer.PlayerLevel
                                txtJoinDate.Text = objExistingPlayer.JoinDate.ToString("MM/dd/yy hh:mm tt")
                            End If

                        End If

                    End If

                Next

                If Not (boolIsChecked) Then
                    ManagePageState(PageState.View)
                End If

            ElseIf (sender.Equals(lnkDelete)) Then

                For Each currentPlayer As DataGridItem In grdPlayers.Items

                    If (currentPlayer.ItemType.Equals(ListItemType.Item)) Or (currentPlayer.ItemType.Equals(ListItemType.AlternatingItem)) Then

                        Dim chkPlayer As CheckBox = currentPlayer.FindControl("chkPlayer")
                        Dim lblPlayerID As Label = currentPlayer.FindControl("lblPlayerID")

                        If (chkPlayer.Checked) Then
                            tss_DKP.tss_DeletePlayer(CInt(lblPlayerID.Text))
                        End If

                    End If

                Next

                ManagePageState(PageState.View)

            ElseIf (sender.Equals(lnkSync)) Then

                Dim strWarning As String = SyncPlayers()
                ManagePageState(PageState.View)
                lblWarning.Text = strWarning

            ElseIf (sender.Equals(lnkSubmit)) Then

                If (vsPageState = PageState.Add) Then

                    If (txtPlayerName.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Player name can not be empty."
                    ElseIf (txtPlayerRank.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Player rank can not be empty."
                    ElseIf (ddlPlayerClass.SelectedValue.Length = 0) Then
                        lblWarning.Text = "Error: Player class can not be empty."
                    ElseIf (ddlPlayerRace.SelectedValue.Length = 0) Then
                        lblWarning.Text = "Error: Player race can not be empty."
                    ElseIf (ddlPlayerLevel.SelectedValue.Length = 0) Then
                        lblWarning.Text = "Error: Player level can not be empty."
                    ElseIf (txtJoinDate.Text.Trim.Length = 0) Then
                        lblWarning.Text = "Error: Join date can not be empty."
                    ElseIf Not IsDate(txtJoinDate.Text) Then
                        lblWarning.Text = "Error: Join date is not a valid date."
                    Else

                        Dim objNewPlayer As New tss_PlayerInfo : objNewPlayer = CBO.InitializeObject(objNewPlayer, GetType(tss_PlayerInfo))

                        objNewPlayer.PlayerName = txtPlayerName.Text.Trim
                        objNewPlayer.PlayerRank = txtPlayerRank.Text.Trim
                        objNewPlayer.PlayerClass = ddlPlayerClass.SelectedValue
                        objNewPlayer.PlayerRace = ddlPlayerRace.SelectedValue
                        objNewPlayer.PlayerLevel = ddlPlayerLevel.SelectedValue
                        objNewPlayer.JoinDate = txtJoinDate.Text.Trim
                        objNewPlayer.BoardID = CInt(Settings("BoardID"))

                        Try
                            tss_DKP.tss_AddPlayer(objNewPlayer)
                        Catch ex As ApplicationException
                            lblWarning.Text = "Error: Trying to add player resulted in the following error (" + ex.Message + ")."
                        End Try

                    End If

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.SingleUpdate) Then

                    For Each currentPlayer As DataGridItem In grdPlayers.Items

                        If (currentPlayer.ItemType.Equals(ListItemType.Item)) Or (currentPlayer.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkPlayer As CheckBox = currentPlayer.FindControl("chkPlayer")
                            Dim lblPlayerID As Label = currentPlayer.FindControl("lblPlayerID")

                            If (chkPlayer.Checked) Then

                                Dim objExistingPlayer As tss_PlayerInfo = tss_DKP.tss_GetPlayer(CInt(lblPlayerID.Text))

                                If (objExistingPlayer Is Nothing) Then
                                    lblWarning.Text = "Error: Trying to update player resulted in the following error (Player in selection not found.)."
                                Else

                                    objExistingPlayer.PlayerName = txtPlayerName.Text.Trim
                                    objExistingPlayer.PlayerRank = txtPlayerRank.Text.Trim
                                    objExistingPlayer.PlayerClass = ddlPlayerClass.SelectedValue
                                    objExistingPlayer.PlayerRace = ddlPlayerRace.SelectedValue
                                    objExistingPlayer.PlayerLevel = ddlPlayerLevel.SelectedValue
                                    objExistingPlayer.JoinDate = txtJoinDate.Text.Trim

                                    Try
                                        tss_DKP.tss_UpdatePlayer(objExistingPlayer)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = "Error: Trying to update player resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                ElseIf (vsPageState = PageState.MultiUpdate) Then

                    For Each currentPlayer As DataGridItem In grdPlayers.Items

                        If (currentPlayer.ItemType.Equals(ListItemType.Item)) Or (currentPlayer.ItemType.Equals(ListItemType.AlternatingItem)) Then

                            Dim chkPlayer As CheckBox = currentPlayer.FindControl("chkPlayer")
                            Dim lblPlayerID As Label = currentPlayer.FindControl("lblPlayerID")

                            If (chkPlayer.Checked) Then

                                Dim objExistingPlayer As tss_PlayerInfo = tss_DKP.tss_GetPlayer(CInt(lblPlayerID.Text))

                                If (objExistingPlayer Is Nothing) Then
                                    lblWarning.Text = lblWarning.Text + IIf(lblWarning.Text.Length > 0, "<br>", "") _
                                        + "Error: Trying to update player resulted in the following error (Player in selection not found.)."
                                Else

                                    If (chkIncludePlayerRank.Checked) Then
                                        objExistingPlayer.PlayerRank = txtPlayerRank.Text.Trim
                                    End If

                                    If (chkIncludePlayerClass.Checked) Then
                                        objExistingPlayer.PlayerClass = ddlPlayerClass.SelectedValue
                                    End If

                                    If (chkIncludePlayerRace.Checked) Then
                                        objExistingPlayer.PlayerRace = ddlPlayerRace.SelectedValue
                                    End If

                                    If (chkIncludePlayerLevel.Checked) Then
                                        objExistingPlayer.PlayerLevel = ddlPlayerLevel.SelectedValue
                                    End If

                                    If (chkIncludeJoinDate.Checked) Then
                                        objExistingPlayer.JoinDate = txtJoinDate.Text.Trim
                                    End If

                                    Try
                                        tss_DKP.tss_UpdatePlayer(objExistingPlayer)
                                    Catch ex As ApplicationException
                                        lblWarning.Text = lblWarning.Text + IIf(lblWarning.Text.Length > 0, "<br>", "") _
                                            + "<br>Error: Trying to update player (" + objExistingPlayer.PlayerName _
                                            + ") resulted in the following error (" + ex.Message + ")."
                                    End Try

                                End If

                            End If

                        End If

                    Next

                    If (lblWarning.Text = Null.NullString) Then
                        ManagePageState(PageState.View)
                    End If

                End If

            ElseIf (sender.Equals(lnkCancel)) Then

                ManagePageState(PageState.View)

            End If

        End Sub

#End Region

#Region "Public Methods"

        Public Sub Initialize()

            ManagePageState(PageState.View)

        End Sub

#End Region

    End Class

End Namespace
